package com.example.androidlearning.sy10.sy2sqlite;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.androidlearning.R;

import java.util.List;
import java.util.Map;

public class Sy1002_ResultActivity extends AppCompatActivity implements Sy1002_ContentAdapter.Callback {

    private ListView show;
    private MyDatabaseHelper dbHelper;
    private List<Map<String, String>> list = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sy1002_result);
        setTitle("显示和删除");

        show = findViewById(R.id.show);
        dbHelper = new MyDatabaseHelper(this, "myDict.db3", 7);

        updateListBody();// 设置列表内容
        show.setOnItemClickListener(itemClickListener);
    }

    private List<Map<String, String>> getData() {
        Cursor cursor = dbHelper.getReadableDatabase()
                .rawQuery("SELECT * FROM user_info", null);
        return Sy1002_MainSQLite.converCursorToList(cursor);
    }

    private void updateListBody() {
        list = getData();
        show.setAdapter(new Sy1002_ContentAdapter(this, list, this));
    }

    // 第position项被单击时激发该方法
    AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener() {
        /*
         *如果你的自定义ListViewItem中有Button或者Checkable的子类控件的话，
         * 那么默认focus是交给了子控件，而ListView的Item能被选中的基础是它能获取Focus，
         * 也就是说我们可以通过将ListView中Item中包含的所有控件的focusable属性设置为false，
         * 这样的话ListView的Item自动获得了Focus的权限，也就可以被选中了，
         * 也就会响应onItemClickListener中的onItemClick()方法，
         * 然而将ListView的Item Layout的子控件focusable属性设置为false有点繁琐，
         * 我们可以通过对Item Layout的根控件设置其
         * android:descendantFocusability=”blocksDescendants”即可，
         * 这样Item Layout就屏蔽了所有子控件获取Focus的权限，
         * 不需要针对Item Layout中的每一个控件重新设置focusable属性了，
         * 如此就可以顺利的响应onItemClickListener中的onItenClick()方法了。
         */
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            ShowDetailDialog(position);
            Toast.makeText(Sy1002_ResultActivity.this,
                    list.get(position).get("name") + "被单击了", Toast.LENGTH_SHORT).show();
        }
    };

    @Override
    public void click(View view) {
        Toast.makeText(Sy1002_ResultActivity.this,
                (int) view.getTag() + "被单击了", Toast.LENGTH_SHORT).show();
        showDeleteDialg((int) view.getTag());
    }

    public void ShowDetailDialog(int position) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle("详细")
                .setMessage(getDetailInfo(list.get(position)));
        setCloseButton(builder); // 为AlertDialog.Builder添加“关闭”按钮
        setDeleteButton(builder, position)   // 为AlertDialog.Builder添加“删除”按钮
                .create()
                .show();
    }

    public void showDeleteDialg(int position) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle("删除确认").setMessage("确认删除吗？");
        setConfirmDeletionButton(builder, position);
        setCancelButton(builder).create().show();
    }

    private AlertDialog.Builder setCloseButton(
            AlertDialog.Builder builder) {
        // 调用setPositiveButton方法添加“确定”按钮
        return builder.setPositiveButton("关闭", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(Sy1002_ResultActivity.this,
                        "关闭详细", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private AlertDialog.Builder setConfirmDeletionButton(
            AlertDialog.Builder builder, final int position) {
        // 调用setPositiveButton方法添加“确定”按钮
        return builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                int count = dbHelper.getReadableDatabase()
                        .delete("user_info", "_account = ?",
                                new String[]{list.get(position).get("account")});
                if (count > 0) {
                    Toast.makeText(Sy1002_ResultActivity.this,
                            "删除成功", Toast.LENGTH_SHORT).show();
                    updateListBody();
                }
            }
        });
    }

    private AlertDialog.Builder setDeleteButton(
            AlertDialog.Builder builder, final int position) {
        // 调用setNegativeButton方法添加“取消”按钮
        return builder.setNegativeButton("删除", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                showDeleteDialg(position);
                Toast.makeText(Sy1002_ResultActivity.this, "删除信息", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private AlertDialog.Builder setCancelButton(
            AlertDialog.Builder builder) {
        // 调用setNegativeButton方法添加“取消”按钮
        return builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(Sy1002_ResultActivity.this, "取消", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private String getDetailInfo(Map<String, String> content) {
        String account = content.get("account");
        String name = content.get("name");
        String email = content.get("email");
        String tel = content.get("tel");
        String work = content.get("work");

        String detail = "";
        detail += "账号：";
        detail += account.equals("") ? "空" : account;
        detail += "\n姓名：";
        detail += name.equals("") ? "空" : name;
        detail += "\n邮箱：";
        detail += email.equals("") ? "空" : email;
        detail += "\n电话：";
        detail += tel.equals("") ? "空" : tel;
        detail += "\n职位：";
        detail += work.equals("") ? "空" : work;
        return detail;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dbHelper.close();
    }
}
